'''
Created on Jan 17, 2010

@author: roman
'''

import re
import common
import urlparse
from utils import isImageHosting
from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def replaceHashTagsFunction(what):
    searchFor = what.group(0).replace("#", "%23")
    return '<a href="http://twitter.com/search?q=%s">%s</a>' % (searchFor, what.group(0)) 

def replaceHashTags(text):
    return  re.sub('(#[\w+]*)', replaceHashTagsFunction, text)

def replaceTwiNamesFunction(what):
    username = what.group(0).replace("@", "")
    return '<a href="http://twitter.com/%s">@%s</a>' % (username,username)

def replaceTwiUsers(text):
    return re.sub('(@[\w+]*)', replaceTwiNamesFunction, text)

def twitterise(text):
    return replaceHashTags(replaceTwiUsers(text))

def image(url):
    if url.find('http://twitpic') != -1:
         imageId = url.split('/')[-1]
         img = 'http://twitpic.com/show/thumb/%s' % imageId
         return '<a href="%s" border="0"><img src="%s"/></a>' % (url, img)
    elif url.find('yfrog') != -1:
         img = url + '.th.jpg'
         return '<a href="%s" border="0"><img src="%s"/></a>' % (url, img)
    elif url.find('moby') != -1:
         img = 'http://api.mobypicture.com?t=%s&s=small&k=%s&format=plain' % (url, common.MOBYPIC_API_KEY)
         return '<a href="%s" border="0"><img src="%s"/></a>' % (url, img)

register.filter(twitterise)
register.filter(isImageHosting)
register.filter(image)